package com.nnhx;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicLong;


@RestController
@RequestMapping("/seckill")
public class SeckillGoodsController {

	private  static AtomicLong count = new AtomicLong();

	private static long time = System.currentTimeMillis();

	@Value("${test.min}")
	private Long MIN;
	@Value("${test.max}")
	private Long MAX;

	@PostConstruct
	public void getInit(){
		System.out.println(MIN);
		System.out.println(MAX);
	}

	@PostMapping("/goods/test")
	public String test(){
		long l = count.incrementAndGet();

		if ( l <=MAX){
			System.out.println(l);
		}

		if (MIN.equals(l)){
			System.out.println("达到指定并发数量了 " +
					MIN +
					"，开始计时----------->");
			time = System.currentTimeMillis();
		}
		if (MAX.equals(l)){
			System.out.println("达到测试最大样本数了 " +
					MAX+
					"，计时---------->");
			long diff = System.currentTimeMillis() - time;
			System.out.println(diff);
		}

		return "{\n" +
				"    \"code\": 200,\n" +
				"    \"status\": true,\n" +
				"    \"message\": \"操作成功.\",\n" +
				"    \"body\": \"success  " +
				l +
				"\" ,\n" +
				"    \"timestamp\": 1598444240097\n" +
				"}";
	}

	@GetMapping("/goods/set/{c}")
	public String setCount(@PathVariable("c") Long c){
		count.set(c);
		long l = count.get();
		System.out.println(l);
		return String.valueOf(l);
	}

	@GetMapping("/goods/getIni")
		public String getIni(){
			System.out.println(MIN);
			System.out.println(MAX);
			return "min: " + MIN + "  max: " + MAX;
		}


	public static void main(String[] args) {
		test1();
	}

	private static void test1() {
		Thread[]  threads = new Thread[3000];
		CountDownLatch latch = new CountDownLatch(threads.length);

		for(int i = 0; i<threads.length; i++){
			threads[i]  =  new  Thread(()->{
				latch.countDown();
				try {
					latch.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				for(int j=0; j<100; j++){
					long l = count.incrementAndGet();
					System.out.println(l);
				}
			});
		}
		for(int i= 0; i<threads.length; i++){
			threads[i].start();
		}
	}


}
